package com.cms.kernel.shiro.velocity;

import org.apache.velocity.context.Context;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.ToolManager;
import org.apache.velocity.tools.ToolboxFactory;
import org.apache.velocity.tools.view.ViewToolContext;
import org.springframework.web.servlet.view.velocity.VelocityToolboxView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Copyright (C) 2013 2016 Well
 * 文件:ShiroVelocityView.java
 * 创建:Well
 * 日期:2016年6月23日 下午2:19:30
 * 来自:
 * 版本:
 * 描述:shiro-velocity的工具栏视图
 *      重写 org.springframework.web.servlet.view.velocity.VelocityToolboxView 中的 createVelocityContext 方法
 *      实现在velocity中支持shiro标签，使用velocity中的shiro标签参考shiro-velocity-support.txt
 */

public class ShiroVelocityView extends VelocityToolboxView
{

    @Override
    protected Context createVelocityContext(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        ViewToolContext context=new ViewToolContext(super.getVelocityEngine(),request,response,super.getServletContext());
        context.putAll(model);
        if(null!=this.getToolboxConfigLocation())
        {
            ToolManager toolManager=new ToolManager();
            toolManager.setVelocityEngine(super.getVelocityEngine());
            toolManager.configure(super.getServletContext().getRealPath(super.getToolboxConfigLocation()));
            ToolboxFactory toolboxFactory=toolManager.getToolboxFactory();
            if(toolboxFactory.hasTools(Scope.REQUEST))
            {
                context.addToolbox(toolboxFactory.createToolbox(Scope.REQUEST));
            }
            if(toolboxFactory.hasTools(Scope.APPLICATION))
            {
                context.addToolbox(toolboxFactory.createToolbox(Scope.APPLICATION));
            }
            if(toolboxFactory.hasTools(Scope.SESSION))
            {
                context.addToolbox(toolboxFactory.createToolbox(Scope.SESSION));
            }
        }

        return context;
    }
}
